<template>
  <div class="article-management animate__animated animate__fadeIn">
    <!-- 文章列表视图 -->
    <div v-if="!showEditor" class="articles-list">
      <!-- 切换选项和搜索框 -->
      <div class="tab-container">
        <div class="tab-buttons">
          <button 
            :class="['tab-button', { active: activeTab === 'published' }]"
            @click="switchTab('published')"
          >
            已发布文章
          </button>
          <button 
            :class="['tab-button', { active: activeTab === 'draft' }]"
            @click="switchTab('draft')"
          >
            草稿箱
          </button>
        </div>
        <div class="search-container">
          <input
            v-model="searchKeyword"
            type="text"
            placeholder="搜索文章标题或简介..."
            class="search-input"
            @input="handleSearch"
          />
          <button class="search-button" @click="handleSearch">
            <t-icon name="search" />
          </button>
        </div>
      </div>

      <div v-for="article in articles" :key="article.id" class="article-item animate__animated animate__fadeIn">
        <div class="article-main" @click="goToArticle(article.id)">
          <div class="article-header">
            <h3 class="article-title" v-html="highlightKeyword(article.title)"></h3>
            <span :class="['status-tag', article.status === 'PUBLISHED' ? 'published' : 'draft']">
              {{ article.status === 'PUBLISHED' ? '已发布' : '草稿' }}
            </span>
          </div>
          <p class="article-description" v-html="highlightKeyword(article.description)"></p>
          <div class="article-meta">
            <span class="meta-item">
              <t-icon name="heart" /> {{ article.likeCount }}
            </span>
            <span class="meta-item">
              <t-icon name="star" /> {{ article.favoriteCount }}
            </span>
            <span class="meta-item">
              <t-icon name="chat" /> {{ article.commentCount }}
            </span>
            <span class="meta-item">
              <t-icon name="time" /> {{ formatDate(article.createdAt) }}
            </span>
          </div>
        </div>
        <button class="edit-button" @click="editArticle(article.id)">
          <t-icon name="edit" /> 编辑
        </button>
      </div>
    </div>

    <!-- 编辑器视图 -->
    <div v-else class="editor-view animate__animated animate__fadeIn">
      <div class="editor-header">
        <button class="back-button" @click="showEditor = false">
          <t-icon name="arrow-left" /> 返回列表
        </button>
      </div>
      
      <div class="input-section">
        <input
          v-model="editingArticle.title"
          type="text"
          placeholder="请输入文章标题"
          class="title-input"
        />
        <textarea
          v-model="editingArticle.description"
          placeholder="请输入文章概述"
          class="description-input"
        ></textarea>
      </div>

      <div class="editor-wrapper">
        <Toolbar
          style="border-bottom: 1px solid #dcdfe6"
          :editor="editorRef"
          :defaultConfig="toolbarConfig"
          :mode="mode"
        />
        <Editor
          style="height: calc(100vh - 500px); overflow-y: hidden;"
          v-model="editingArticle.content"
          :defaultConfig="editorConfig"
          :mode="mode"
          @onCreated="handleCreated"
        />
      </div>

      <div class="action-buttons">
        <button class="save-button" @click="handleSave">
          <t-icon name="save" /> 保存修改
        </button>
        <button 
          :class="['status-button', editingArticle.status === 'DRAFT' ? 'publish' : 'unpublish']"
          @click="handleStatusChange"
        >
          <t-icon :name="editingArticle.status === 'DRAFT' ? 'send' : 'send-cancel'" />
          {{ editingArticle.status === 'DRAFT' ? '发布文章' : '取消发布' }}
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import '@wangeditor/editor/dist/css/style.css'
import { ref, shallowRef, onMounted, onBeforeUnmount } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/userStore'
import { storeToRefs } from 'pinia'
import { getPublishedArticlesByUserIdOrderByDESC, getDraftArticlesByUserIdOrderByDESC, findArticleById, updateArticle, updateArticleStatus, getArticlesByUserIdAndKeyWordOrderByDESC } from '@/api/articleApi'
import { ElMessage } from 'element-plus'

const router = useRouter()
const userStore = useUserStore()
const { profile } = storeToRefs(userStore)

// 编辑器配置
const editorRef = shallowRef()
const mode = 'default'
const toolbarConfig = {}
const editorConfig = { placeholder: '请输入内容...' }

// 组件状态
const activeTab = ref('published')
const articles = ref([])
const showEditor = ref(false)
const searchKeyword = ref('')
const editingArticle = ref({
  title: '',
  description: '',
  content: '',
  status: ''
})

// 高亮关键词
const highlightKeyword = (text) => {
  if (!searchKeyword.value) return text
  const regex = new RegExp(searchKeyword.value, 'gi')
  return text.replace(regex, match => `<span class="highlight">${match}</span>`)
}

// 切换标签页
const switchTab = async (tab) => {
  activeTab.value = tab
  searchKeyword.value = ''
  await loadArticles()
}

// 加载文章列表
const loadArticles = async () => {
  try {
    let response
    if (searchKeyword.value) {
      response = await getArticlesByUserIdAndKeyWordOrderByDESC(profile.value.id, searchKeyword.value, 1, 10)
    } else {
      response = activeTab.value === 'published'
        ? await getPublishedArticlesByUserIdOrderByDESC(profile.value.id, 1, 10)
        : await getDraftArticlesByUserIdOrderByDESC(profile.value.id, 1, 10)
    }
    articles.value = response.data
  } catch (error) {
    console.error('加载文章失败:', error)
    ElMessage.error('加载文章失败')
  }
}

// 处理搜索
const handleSearch = async () => {
  await loadArticles()
}

// 跳转到文章详情
const goToArticle = (id) => {
  router.push(`/home/article/${id}`)
}

// 编辑文章
const editArticle = async (id) => {
  try {
    const response = await findArticleById(id)
    editingArticle.value = response.data
    showEditor.value = true
  } catch (error) {
    console.error('加载文章详情失败:', error)
    ElMessage.error('加载文章详情失败')
  }
}

// 处理保存
const handleSave = async () => {
  try {
    const data = {
      title: editingArticle.value.title,
      description: editingArticle.value.description,
      userId: profile.value.id,
      content: editingArticle.value.content,
      status: editingArticle.value.status
    }
    await updateArticle(data, editingArticle.value.id)
    ElMessage.success('保存成功')
    await loadArticles()
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  }
}

// 处理状态变更
const handleStatusChange = async () => {
  try {
    const newStatus = editingArticle.value.status === 'DRAFT' ? 'PUBLISHED' : 'DRAFT'
    await updateArticleStatus(editingArticle.value.id, newStatus)
    editingArticle.value.status = newStatus
    ElMessage.success(newStatus === 'PUBLISHED' ? '文章已发布' : '文章已转为草稿')
    await loadArticles()
  } catch (error) {
    console.error('状态更新失败:', error)
    ElMessage.error('状态更新失败')
  }
}

// 格式化日期
const formatDate = (date) => {
  return new Date(date).toLocaleDateString()
}

// 编辑器相关
const handleCreated = (editor) => {
  editorRef.value = editor
}

onMounted(() => {
  loadArticles()
})

onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})
</script>

<style scoped>
.article-management {
  padding: 20px;
  background-color: #f8f9fa;
  min-height: 100vh;
}

.tab-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.tab-buttons {
  display: flex;
  gap: 15px;
}

.tab-button {
  padding: 12px 24px;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  background-color: #fff;
  color: #666;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.tab-button.active {
  background-color: #409eff;
  color: white;
}

.search-container {
  display: flex;
  gap: 10px;
}

.search-input {
  padding: 10px 15px;
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  font-size: 14px;
  width: 250px;
  transition: all 0.3s ease;
}

.search-input:focus {
  border-color: #409eff;
  outline: none;
}

.search-button {
  padding: 10px 20px;
  border: none;
  border-radius: 8px;
  background-color: #409eff;
  color: white;
  cursor: pointer;
  transition: all 0.3s ease;
}

.search-button:hover {
  background-color: #66b1ff;
}

.articles-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.article-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  transition: transform 0.3s ease;
}

.article-item:hover {
  transform: translateY(-2px);
}

.article-main {
  flex: 1;
  cursor: pointer;
}

.article-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.article-title {
  margin: 0;
  color: #333;
}

.status-tag {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.status-tag.published {
  background-color: #67c23a;
  color: white;
}

.status-tag.draft {
  background-color: #909399;
  color: white;
}

.article-description {
  color: #666;
  margin: 0 0 15px 0;
}

.article-meta {
  display: flex;
  gap: 20px;
  color: #999;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 5px;
}

.edit-button {
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  background-color: #409eff;
  color: white;
  cursor: pointer;
  transition: all 0.3s ease;
}

.edit-button:hover {
  background-color: #66b1ff;
}

.editor-view {
  background-color: white;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.editor-header {
  margin-bottom: 20px;
}

.back-button {
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  background-color: #f4f4f5;
  color: #606266;
  cursor: pointer;
  transition: all 0.3s ease;
}

.back-button:hover {
  background-color: #e9e9eb;
}

.input-section {
  margin-bottom: 20px;
}

.title-input,
.description-input {
  width: 100%;
  padding: 12px;
  margin-bottom: 15px;
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  font-size: 16px;
}

.description-input {
  min-height: 100px;
  resize: vertical;
}

.editor-wrapper {
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  margin-bottom: 20px;
}

.action-buttons {
  display: flex;
  gap: 15px;
  justify-content: flex-end;
}

.save-button,
.status-button {
  padding: 12px 24px;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.save-button {
  background-color: #67c23a;
  color: white;
}

.save-button:hover {
  background-color: #85ce61;
}

.status-button.publish {
  background-color: #409eff;
  color: white;
}

.status-button.unpublish {
  background-color: #f56c6c;
  color: white;
}

.status-button:hover {
  opacity: 0.9;
}

:deep(.highlight) {
  color: #f56c6c;
  font-weight: bold;
}
</style>
